var qs = require("querystring")
var jwt = require("jsonwebtoken");
const { request } = require("https");
module.exports=async (resquest,response)=>{
    var method = resquest.method;
    var url = resquest.url; //path?query#hash
    var path = url.split("?")[0];//path
    var query_hash = url.split("?")[1];//query#hash
    var query = ""
    if(query_hash){query = query_hash.split("#")[0];}//query

    //路由开始 不需要验证token
    if(path === "/api/blog/list" && method === "GET"){
        //允许跨域
        response.setHeader("Access-Control-Allow-Origin","http://127.0.0.1:5500")
        //获取postman传递来的数据
        var queryObj = qs.parse(query);
        var author = queryObj.author;
        var keyword = queryObj.keyword;

        //查数据库 
        var sql = "select id,title,author from blogs where 1=1 ";
        if(author){sql+= `and author = '${author}' `};
        if(keyword){sql+= `and title like '%${keyword}%' `};

        var data = "";
        data = await new Promise((reslove,reject)=>{
            global.connection.query(sql, (error, results)=> {
                if (error) {
                    reject(error)
                }else{
                    reslove(results)
                }
            });
        }) 
        return {
            message:"/api/blog/list",
            data:data
        };
    }
    if(path==="/api/blog/detail" && method==="GET" ){
        //获取一篇博客的内容 返回指定的博客
        //获取postman传递来的数据
        var queryObj = qs.parse(query);
        var id = queryObj.id;

        //查数据库 
        var sql = `select content from blogs where id=${id} `;

        var data = "";
        data = await new Promise((reslove,reject)=>{
            global.connection.query(sql, (error, results)=> {
                if (error) {
                    reject(error)
                }else{
                    reslove(results)
                }
            });
        }) 
        return {
            message:"/api/blog/list",
            data:data[0] === undefined ? "" : data[0].content
        };
    }

    // 需要验证token (前端token是存储在请求体中)
    if(path==="/api/blog/new" && method==="POST" ){
        try {
            //获取postman传递来的数据
            var bodyObj = await new Promise((reslove,reject)=>{
                var body = "";
                var bodyObj = "";
                resquest.on("data",(data)=>{
                    body += data.toString()
                })
                resquest.on("end",()=>{
                    bodyObj = JSON.parse(body);
                    reslove(bodyObj)
                })
            })
            var {token} = bodyObj;
            //检验token!!
            var decoded = jwt.verify(token,"damulovezdy")
            if(decoded.username){
                //数据库新增操作 
                var author = decoded.username;
                var {title,content,createtime} = bodyObj;
                var sql = 
                    "INSERT INTO blogs (title,content,author,createtime) " + 
                    `VALUES ('${title}','${content}','${author}','${createtime}')`;
                
                var data = "";
                data = await new Promise((reslove,reject)=>{
                    global.connection.query(sql, (error, results)=> {
                        if (error) {
                            reject(error)
                        }else{
                            reslove(results)
                        }
                    });
                }) 
                return {
                    message:"/api/blog/new",
                    data:data
                };
            }
        } catch (error) {
            return{
                message:"token is error",
                data:"error"
            }
        }
    }
    if(path==="/api/blog/update" && method==="POST"){
       try {
            //更新一篇博客  返回更新完的那个博客
            //获取postman传递来的数据
            var queryObj = qs.parse(query);
            var bodyObj = await new Promise((reslove,reject)=>{
                var body = "";
                var bodyObj = "";
                resquest.on("data",(data)=>{
                    body += data.toString()
                })
                resquest.on("end",()=>{
                    bodyObj = JSON.parse(body);
                    reslove(bodyObj)
                })
            })
            //检验token
            var {token} = bodyObj;
            var decoded = jwt.verify(token,"damulovezdy");
            if(decoded.username){
                //检验通过 代表处于登录状态!! 且登录是有效的
                var id = queryObj.id;
                //检查登录的用户 与 当前需要修改的博客作者是否一致
                var sql = `select author from blogs where id=${id} `;
                var data1 = "";
                data1 = await new Promise((reslove,reject)=>{
                    global.connection.query(sql, (error, results)=> {
                        if (error) {
                            reject(error)
                        }else{
                            reslove(results)
                        }
                    });
                }) 
                if(data1[0]){
                    //id是正确的 更新的数据是存在的
                    var author = data1[0].author;
                    if(author === decoded.username){
                        //数据库更新操作 
                        var {title,content} = bodyObj;
                        var updatSQL = "";
                        if(title){updatSQL+=`title ="${title}",`};
                        if(content){updatSQL+=`content ="${content}",`};

                        updatSQL = updatSQL.substring(0,updatSQL.length-1)
                        var sql = 
                            "UPDATE blogs SET "+ updatSQL + ` where id=${id}`
                        
                        var data = "";
                        data = await new Promise((reslove,reject)=>{
                            global.connection.query(sql, (error, results)=> {
                                if (error) {
                                    reject(error)
                                }else{
                                    reslove(results)
                                }
                            });
                        }) 
                        return {
                            message:"/api/blog/update",
                            data:data
                        };
                    }else{
                        return{
                            data:"error",
                            message:"username is not author"
                        }
                    }
                }else{
                    //id是错误的 更新的数据不存在
                    return{
                        data:"error",
                        message:"id is error"
                    }
                }
            }
       } catch (error) {
            return{
                message:"token is error",
                data:"error"
            }
       }
    }
    // 需要验证token (前端token是存储在cookie中)
    if(path==="/api/blog/del" && method==="GET"){
        //从cookie中拿token
        var token = "";
        var cookie = resquest.headers.cookie;
        var arr = cookie.split(";");
        for(var i=0;i<arr.length;i++){
            var arr2 = arr[i].split("=");
            var key = arr2[0];
            key = key.trim()
            var val = arr2[1];
            if(key === "token"){
                token = val;
            }
        }

        try {
            //检验token
            var decoded = jwt.verify(token,"damulovezdy")
            if(decoded.username){
                //判断删除的数据是否存在
                var queryObj = qs.parse(query);
                var id = queryObj.id;
                var sql = `select author from blogs where id=${id} `;
                var data1 = "";
                data1 = await new Promise((reslove,reject)=>{
                    global.connection.query(sql, (error, results)=> {
                        if (error) {
                            reject(error)
                        }else{
                            reslove(results)
                        }
                    });
                }) 
                if(data1.length === 0){
                    return {
                        message:"data is empty",
                        data:"error"
                    }
                }
                //token没有问题 检验要删除的blog是否是登录用户的
                var author = data1[0].author;
                if(decoded.username !== author){
                    return {
                        message:"username is not author",
                        data:"error"
                    }
                }

                //真正的删除(软删除)
                var sql = `delete from blogs  where id=${id}`;
                var data = "";
                data = await new Promise((reslove,reject)=>{
                    global.connection.query(sql, (error, results)=> {
                        if (error) {
                            reject(error)
                        }else{
                            reslove(results)
                        }
                    });
                }) 

                return {
                    message:"/api/blog/del",
                    data:data
                }
            }
        } catch (error) {
            return {
                message:"token is error",
                data:"error"
            }
        }
    }
     
    
}